package com.gjzt.business.bid.service;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eastdigit.servlet.ReqBean;
import com.eastdigit.system.model.BusinessException;
import com.eastdigit.system.model.SqlBuilder;
import com.eastdigit.system.service.BaseService;
import com.eastdigit.util.DateUtil;
import com.eastdigit.util.StringUtil;
import com.gjzt.business.bid.inter.BiddingMapper;
import com.gjzt.business.bid.inter.BiddingResourceMapper;
import com.gjzt.business.bid.model.Bidding;
import com.gjzt.business.bid.model.BiddingResource;
import com.gjzt.business.utils.Constant;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class BiddingService extends BaseService {

	@Autowired
	private BiddingMapper biddingMapper;
	@Autowired
	private BiddingResourceMapper biddingResourceMapper;
	private static final String FIRST_FLOOR_ICON_OPEN = "./assets/admin/img/ztree/dept_open.png"; 
	private static final String FIRST_FLOOR_ICON_CLOSE = "./assets/admin/img/ztree/dept_close.png";
	private static final String SECOND_FLOOR_ICON_OPEN = "./assets/admin/img/ztree/pos_open.png"; 
	private static final String SECOND_FLOOR_ICON_CLOSE = "./assets/admin/img/ztree/pos_close.png"; 
	private static final String THIRD_FLOOR_ICON = "./assets/admin/img/ztree/user.png";
	
	private static final DecimalFormat df = new DecimalFormat("0.00");//格式化小数   


	/**
	 * 查询
	 *
	 * @param reqBean
	 * @return
	 */
	public JSONObject findAdBidding(ReqBean reqBean) {
		SqlBuilder sqlBuilder = new SqlBuilder("select ab.* ,ac.CUSTOMER_NAME"
				+ " from AD_BIDDING  ab LEFT JOIN AD_CUSTOMER ac on ab.CUSTOMER_ID=ac.CUSTOMER_ID where 1=1");
		if (Constant.QUICK_SEARCH_FALSE.equals(reqBean.getInfo("quickSearch"))) {// 正常查询
			sqlBuilder.addWhereLike2("ab.BID_TITLE", reqBean.getInfo("bidTitle"))
					.addWhere("ab.STATUS", reqBean.getInfo("status"))
					.addTimeWhere("ab.START_DATE", reqBean.getInfo("startDate"), ">=")
					.addTimeWhere("ab.END_DATE", reqBean.getInfo("endDate"), "<=");
		} else {
			sqlBuilder.addWhereLike2("BID_TITLE", reqBean.getInfo("quickSearchBidTitle"));
		}
		sqlBuilder.appendSql(" order by ab.PUBLISH_TIME desc", null);
		return this.queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
	}

	/**
	 * 新增
	 *
	 * @param reqBean
	 */
	public JSONObject addAdBidding(ReqBean reqBean) {
		JSONObject json = new JSONObject();
		Bidding bidding = getAdBidding(reqBean);
		bidding.setBidId(intIncrementId("AD_BIDDING", "BID_ID"));
		bidding.setStatus(Constant.BID_STATUS_UNPUBLISHED);
		bidding.setCreateTime(new Date());
		biddingMapper.insert(bidding);
		json.put("bidId", bidding.getBidId());
		return json;
	}

	/**
	 * 发布
	 *
	 * @param reqBean
	 */
	public void publishBid(ReqBean reqBean) {
		String bidId = reqBean.getInfo("bidId");
		int days = reqBean.getInfoInt("days");
		if (StringUtil.isEmpty(bidId)) {
			throw new BusinessException("获取主键失败");
		}
		Bidding bid = biddingMapper.selectByPrimaryKey(bidId);
		bid.setStatus(Constant.BIDSTATUS_IN);
		bid.setPublishTime(new Date());

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.DAY_OF_MONTH, days);
		bid.setLimitTime(calendar.getTime());
		biddingMapper.updateByPrimaryKey(bid);
	}

	/**
	 * 修改
	 *
	 * @param reqBean
	 */
	public JSONObject updateAdBidding(ReqBean reqBean) {
		JSONObject json = new JSONObject();
		String bidId = reqBean.getInfo("bidId");
		if (StringUtil.isEmpty(bidId)) {
			throw new BusinessException("获取主键失败");
		}
		Bidding bidding = getAdBidding(reqBean);
		biddingMapper.updateByPrimaryKeySelective(bidding);
		json.put("bidId", bidId);
		return json;
	}

	/**
	 * 删除
	 *
	 * @param reqBean
	 */
	public void removeAdBidding(ReqBean reqBean) {
		String bidId = reqBean.getInfo("bidId");
		if (StringUtil.isEmpty(bidId)) {
			throw new BusinessException("获取主键失败");
		}
		biddingMapper.deleteByPrimaryKey(bidId);
		// 删除竞价单关联的资源
		biddingResourceMapper.deleteByBidId(bidId);
	}
	
	/**
	 * 将数据后面带上小数点
	 * @param number
	 * @return
	 */
	public double formatNumber(String number){
		if(StringUtil.isNotEmpty(number)){
			double number_d = Double.valueOf(number);
			String number_s = df.format(number_d);
			return Double.valueOf(number_s);
		}else {
			return 0.00;
		}
	}

	/**
	 * 从表单获取对象
	 *
	 * @param reqBean
	 * @return
	 */
	private Bidding getAdBidding(ReqBean reqBean) {
		Bidding bidding = new Bidding();
		bidding.setBidId(reqBean.getInfo("bidId"));
		bidding.setBidCode(reqBean.getInfo("bidCode"));
		bidding.setBidTitle(reqBean.getInfo("bidTitle"));
		bidding.setDeposit(formatNumber(reqBean.getInfo("deposit")));
		bidding.setBasePrice(formatNumber(reqBean.getInfo("basePrice")));
		bidding.setIncreasePrice(formatNumber(reqBean.getInfo("increasePrice")));
		bidding.setPublishTime(DateUtil.parseDateTime(reqBean.getInfo("publishTime")));
		bidding.setLimitTime(DateUtil.parseDateTime(reqBean.getInfo("limitTime")));
		bidding.setStatus(reqBean.getInfo("status"));
		bidding.setCustomerId(reqBean.getInfo("customerId"));
		bidding.setBidNotice(reqBean.getInfo("bidNotice"));
		bidding.setWinningPrice(formatNumber(reqBean.getInfo("winningPrice")));

		return bidding;
	}

	public JSONObject queryBidRecord(ReqBean reqBean) {
		SqlBuilder sqlBuilder = new SqlBuilder("SELECT	abr.*,ac.CUSTOMER_NAME FROM AD_BIDDING_RECORD abr "
				+ " LEFT JOIN AD_CUSTOMER ac on abr.CUSTOMER_ID=ac.CUSTOMER_ID where 1=1 ")
						.addWhere("BID_ID", reqBean.getInfo("bidId"))
						.addWhereLike2("ac.CUSTOMER_NAME", reqBean.getInfo("customerName"));
		sqlBuilder.appendSql(" order by abr.BIDDING_TIME desc", null);
		return this.queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
	}

	public JSONObject getBidResourceGroupByTypes(ReqBean reqBean) {
		JSONObject resultJson = new JSONObject();
		JSONArray array = new JSONArray();
		String bidId = reqBean.getInfo("bidId");
		if(StringUtil.isEmpty(bidId)){
			resultJson.put("array", array);
		}else {
			LinkedHashMap<String, JSONArray> resultMap = new LinkedHashMap<String, JSONArray>();
			queryBidResourceOfBus(reqBean, resultMap);
			queryBidResourceOfStop(reqBean, resultMap);

			SqlBuilder sqlBuilder = new SqlBuilder("select * from MEDIA_TYPE mt order by mt.PARENT_ID,mt.MEDIA_ID");
			JSONArray types = this.query(sqlBuilder);
			for (int i = 0; i < types.size(); i++) {
				String mediaId = types.getJSONObject(i).getString("mediaId");
				String mediaName = types.getJSONObject(i).getString("mediaName");
				String parentId = types.getJSONObject(i).getString("parentId");
				JSONObject o = new JSONObject();
				if (resultMap.containsKey(mediaId)) {
					o.put("mediaId", mediaId);
					o.put("mediaName", mediaName);
					o.put("parentId", parentId);
					o.put("resources", resultMap.get(mediaId));
					array.add(o);
				}
			}
			resultJson.put("array", array);
		}
		return resultJson;
	}

	/**
	 * 查询竞价车辆资源
	 * 
	 * @param reqBean
	 * @return
	 */
	public void queryBidResourceOfBus(ReqBean reqBean, LinkedHashMap<String, JSONArray> resultMap) {
		SqlBuilder sqlBuilder = new SqlBuilder(
				"SELECT mt.MEDIA_NAME,mr.RESOURCE_NAME,mr.STOP_ID,mr.BUS_ID,mr.MODEL,mb.LINE_NO,mb.PLATE_NO,mt.PARENT_ID,"
						+ " abr.START_DATE,abr.END_DATE,abr.BID_ID,abr.RESOURCE_ID,mr.MEDIA_TYPE,abr.RESOURCE_PRICE "
						+ " FROM AD_BIDDING_RESOURCE abr "
						+ " LEFT JOIN MEDIA_RESOURCE mr ON abr.RESOURCE_ID = mr.RESOURCE_ID "
						+ " LEFT JOIN MEDIA_TYPE mt on mt.MEDIA_ID=mr.MEDIA_TYPE"
						+ " LEFT JOIN MEDIA_BUS mb on mr.BUS_ID=mb.BUS_ID " + " where 1=1 and mt.PARENT_ID="
						+ Constant.MEDIA_TYPE_BUS).addWhere("abr.BID_ID", reqBean.getInfo("bidId"))
								.addWhereLike2("mr.RESOURCE_NAME", reqBean.getInfo("resourceName"));
		sqlBuilder.appendSql(" order by  mr.MEDIA_TYPE,mb.LINE_NO", null);
		JSONArray resourceOfBusArray = this.query(sqlBuilder);
		for (int i = 0; i < resourceOfBusArray.size(); i++) {
			JSONObject resource = resourceOfBusArray.getJSONObject(i);
			resource.put("startDate", DateUtil.formatDate(DateUtil.parse(resource.getString("startDate"))));
			resource.put("endDate", DateUtil.formatDate(DateUtil.parse(resource.getString("endDate"))));
			String mediaType = resource.getString("mediaType");
			JSONArray resourceArray = new JSONArray();
			if (!resultMap.containsKey(mediaType)) {
				resourceArray.add(resource);
				resultMap.put(mediaType, resourceArray);
			} else {
				resourceArray = resultMap.get(mediaType);
				resourceArray.add(resource);
			}
		}
	}

	/**
	 * 查询竞价站点资源
	 * 
	 * @param reqBean
	 * @return
	 */
	public void queryBidResourceOfStop(ReqBean reqBean, LinkedHashMap<String, JSONArray> resultMap) {
		SqlBuilder sqlBuilder = new SqlBuilder(
				"SELECT mt.MEDIA_NAME,mr.RESOURCE_NAME,mr.BUS_ID,mr.STOP_ID,mr.MODEL,ms.STOP_NAME,ms.ROAD_NAME,mt.PARENT_ID,"
						+ " abr.START_DATE,abr.END_DATE,abr.BID_ID,abr.RESOURCE_ID,mr.MEDIA_TYPE,abr.RESOURCE_PRICE "
						+ " FROM AD_BIDDING_RESOURCE abr "
						+ " LEFT JOIN MEDIA_RESOURCE mr ON abr.RESOURCE_ID = mr.RESOURCE_ID "
						+ " LEFT JOIN MEDIA_TYPE mt on mt.MEDIA_ID=mr.MEDIA_TYPE "
						+ " LEFT JOIN MEDIA_STOP ms on mr.STOP_ID=ms.STOP_ID" + " where 1=1 and mt.PARENT_ID="
						+ Constant.MEDIA_TYPE_STOP).addWhere("abr.BID_ID", reqBean.getInfo("bidId"))
								.addWhereLike2("mr.RESOURCE_NAME", reqBean.getInfo("resourceName"));
		sqlBuilder.appendSql(" order by mr.MEDIA_TYPE, ms.STOP_NAME", null);
		JSONArray resourceOfStopArray = this.query(sqlBuilder);
		for (int i = 0; i < resourceOfStopArray.size(); i++) {
			JSONObject resource = resourceOfStopArray.getJSONObject(i);
			resource.put("startDate", DateUtil.formatDate(DateUtil.parse(resource.getString("startDate"))));
			resource.put("endDate", DateUtil.formatDate(DateUtil.parse(resource.getString("endDate"))));
			String mediaType = resource.getString("mediaType");
			JSONArray resourceArray = new JSONArray();
			if (!resultMap.containsKey(mediaType)) {
				resourceArray.add(resource);
				resultMap.put(mediaType, resourceArray);
			} else {
				resourceArray = resultMap.get(mediaType);
				resourceArray.add(resource);
			}
		}
	}

	// 得到线路车辆map
	public LinkedHashMap<String, JSONArray> getBusOfLineMaps(ReqBean reqBean) {
		LinkedHashMap<String, JSONArray> busOfLineMaps = new LinkedHashMap<String, JSONArray>();
		SqlBuilder getBusSql = new SqlBuilder(
				"SELECT mb.LINE_NO, mb.BUS_ID,mb.PLATE_NO,mb.STATUS from  MEDIA_BUS  mb  where 1=1");
		getBusSql.addWhereLike2("mb.LINE_NO", reqBean.getInfo("lineName"))
		.appendSql(" and mb.COMPANY_ID ='")
		.appendSql(reqBean.getInfo("companyId"))
		.appendSql("'")
		.appendSql(" ORDER BY mb.LINE_NO", null);
		JSONArray buss = this.query(getBusSql);
		for (int i = 0; i < buss.size(); i++) {
			JSONObject bus = buss.getJSONObject(i);
			String lineNo = bus.getString("lineNo");
			JSONArray busArray = new JSONArray();
			if (!busOfLineMaps.containsKey(lineNo)) {
				busArray.add(bus);
				busOfLineMaps.put(lineNo, busArray);
			} else {
				busArray = busOfLineMaps.get(lineNo);
				busArray.add(bus);
			}
		}
		return busOfLineMaps;
	}

	// 得到车辆资源map
	public Map<String, JSONArray> getResourceOfBusMaps(String resourceType) {
		Map<String, JSONArray> resourceOfBusMaps = new HashMap<String, JSONArray>();
		String getResourceSql = "SELECT mr.RESOURCE_ID,mr.RESOURCE_NAME,mr.MEDIA_TYPE,mr.STATUS,mt.MEDIA_NAME,mt.MEDIA_ID, mt.PARENT_ID,mr.BUS_ID,mb.PLATE_NO,mb.LINE_NO  from  MEDIA_RESOURCE  mr "
				+ " LEFT JOIN MEDIA_TYPE mt  on mr.MEDIA_TYPE=mt.MEDIA_ID"
				+ " LEFT JOIN MEDIA_BUS mb on mb.BUS_ID=mr.BUS_ID "
				+ " WHERE mt.PARENT_ID="+Constant.MEDIA_TYPE_BUS+" and mt.STATUS = '" + Constant.DATA_STATUS_TRUE + "'";
		if(StringUtil.isNotEmpty(resourceType)){
			getResourceSql += " and mt.MEDIA_ID="+resourceType;
		}
		getResourceSql +=" order by mt.MEDIA_NAME ";
		JSONArray resources = this.query(getResourceSql);
		for (int i = 0; i < resources.size(); i++) {
			JSONObject resource = resources.getJSONObject(i);
			String busId = resource.getString("busId");
			JSONArray resourceArray = new JSONArray();
			if (!resourceOfBusMaps.containsKey(busId)) {
				resourceArray.add(resource);
				resourceOfBusMaps.put(busId, resourceArray);
			} else {
				resourceArray = resourceOfBusMaps.get(busId);
				resourceArray.add(resource);
			}
		}
		return resourceOfBusMaps;
	}

	// 获取竞价单对应资源
	public Map<String, String> getBidResourceMap(ReqBean reqBean, String resourceType) {
		Map<String, String> billResourceMap = new HashMap<String, String>();
		String bidId = reqBean.getInfo("bidId");
		if (StringUtil.isEmpty(bidId)) {
			return billResourceMap;
		} else {
			// 获得竞价关联资源
			JSONArray bidResourceArray = getResourceOfBid(bidId, resourceType);

			if (bidResourceArray != null && bidResourceArray.size() > 0) {
				for (int i = 0; i < bidResourceArray.size(); i++) {
					JSONObject billResource = bidResourceArray.getJSONObject(i);
					String bidId_v = billResource.getString("bidId");
					String resourceId_k = billResource.getString("resourceId");
					billResourceMap.put(resourceId_k, bidId_v);
				}
			}
			return billResourceMap;
		}
	}
	
	public JSONArray getResourceOfBid(String bidId, String resourceType) {
		String getResourceOfBidSlq = " select  abr.*  from AD_BIDDING_RESOURCE abr "
				+ " LEFT JOIN MEDIA_RESOURCE mr on abr.RESOURCE_ID=mr.RESOURCE_ID "
				+ " LEFT JOIN MEDIA_TYPE mt on mr.MEDIA_TYPE=mt.MEDIA_ID " + " where abr.bid_id=" + bidId
				+ " and mt.MEDIA_ID= " + resourceType;
		return this.query(getResourceOfBidSlq);
	}

	/**
	 * 获取车辆资源树形结构
	 * 
	 * @return
	 */
	public JSONObject getResourceOfBusTree(ReqBean reqBean) {
		// 数据准备
		String resourceType = reqBean.getInfo("resourceType");
		Map<String, String> billResourceMap = getBidResourceMap(reqBean, resourceType);
		LinkedHashMap<String, JSONArray> busOfLineMaps = getBusOfLineMaps(reqBean);
		Map<String, JSONArray> resourceOfBusMaps = getResourceOfBusMaps(resourceType);

		JSONArray array = new JSONArray();
		int i = 1;
		// 循环线路（第一层节点）
		for (Entry<String, JSONArray> entry : busOfLineMaps.entrySet()) {
			// entry (线路对应的车辆)
			// 线路节点
			JSONObject o1 = new JSONObject();
			o1.put("id", i);// todo...  此处id设置有问题 
			o1.put("pId", 0);
			o1.put("name", entry.getKey());

			// 循环线路对应的车辆（第二层节点）
			JSONArray busArray = entry.getValue();
			if(busArray!=null &&busArray.size()>0){
				for (int j = 0; j < busArray.size(); j++) {
					JSONObject bus = busArray.getJSONObject(j);
					// 车辆节点
					JSONObject o2 = new JSONObject();
					o2.put("id", bus.getString("busId"));
					o2.put("pId", i);
					o2.put("name", bus.getString("plateNo"));
					if(!Constant.DATA_STATUS_TRUE.equals(bus.getString("status"))){// 车辆报废、维修
						o2.put("chkDisabled", true);// 无效的资源不能勾选
					}

					// 循环车辆对应的资源（第三层节点）
					JSONArray resourceArray = resourceOfBusMaps.get(bus.getString("busId"));
					if (resourceArray != null) {
						for (int k = 0; k < resourceArray.size(); k++) {
							JSONObject resource = resourceArray.getJSONObject(k);
							// 具体资源节点
							JSONObject o3 = new JSONObject();
							o3.put("id", resource.getString("resourceId"));
							o3.put("pId", resource.getString("busId"));
							o3.put("name", resource.getString("resourceName"));
							o3.put("plateNo", resource.getString("plateNo"));// 线路
							o3.put("lineNo", resource.getString("lineNo"));// 车牌号
							o3.put("mediaId", resource.getString("mediaType"));// 类型id
							o3.put("mediaName", resource.getString("mediaName"));// 类型名称
							o3.put("parentId", resource.getString("parentId"));// 类型父id
							if(Constant.DATA_STATUS_FALSE.equals(resource.getString("status"))){// 资源无效
								o3.put("chkDisabled", true);// 无效的资源不能勾选
							}
							if (billResourceMap.containsKey(resource.getString("resourceId"))) {// 已选择的资源,在树中不显示
								o3.put("chkDisabled ", true);
								/*o3.put("open", true);
								o2.put("checked", true);
								o2.put("open", true);
								o1.put("checked", true);
								o1.put("open", true);*/
							}
							//o3.put("icon", THIRD_FLOOR_ICON);
							array.add(o3);
							
						}
						//o2.put("iconOpen", SECOND_FLOOR_ICON_OPEN);
						//o2.put("iconClose", SECOND_FLOOR_ICON_CLOSE); 
						array.add(o2);
					}
				}
				//o1.put("iconOpen", FIRST_FLOOR_ICON_OPEN);
				//o1.put("iconClose", FIRST_FLOOR_ICON_CLOSE); 
				array.add(o1);
				i++;
			}
		}

		JSONObject result = new JSONObject();
		result.put("array", delHasNoLeafRootNodes(array));
		return result;
	}
	
	//去除没有叶子节点的根节点
	public JSONArray delHasNoLeafRootNodes(JSONArray array){
		
		JSONArray allNodes = new JSONArray();
		JSONArray firstRootNodes = new JSONArray();// 将所有的第一层节点缓存
		JSONArray secondRootNodes = new JSONArray();// 将所有的第二层节点缓存
		for (int i = 0; i < array.size(); i++) {
			if(array.getJSONObject(i).getString("pId").equals("0")){
				firstRootNodes.add(array.getJSONObject(i));
			}else {
				secondRootNodes.add(array.getJSONObject(i));
			}
		}
		for (int k = 0; k < firstRootNodes.size(); k++) {
			boolean flag = false;
			String id =firstRootNodes.getJSONObject(k).getString("id");
			for (int m = 0; m < secondRootNodes.size(); m++) {
				if(secondRootNodes.getJSONObject(m).getString("pId").equals(id)){
					flag = true;
					break;
				}
			}
			if(flag){
				allNodes.add(firstRootNodes.getJSONObject(k));
			}
		}
		for (int n = 0; n < secondRootNodes.size(); n++) {
			allNodes.add(secondRootNodes.getJSONObject(n));
		}
		return allNodes;
	}
	

	// 得到线路车辆map
	public LinkedHashMap<String, JSONObject> getStopMaps(ReqBean reqBean) {
		LinkedHashMap<String, JSONObject> stopMaps = new LinkedHashMap<String, JSONObject>();
		SqlBuilder getStopSql = new SqlBuilder("select ms.STOP_ID,ms.STOP_NAME,ms.`STATUS`  from MEDIA_STOP   ms where 1=1 ");
		getStopSql.addWhereLike2("ms.STOP_NAME", reqBean.getInfo("stopName"));
		JSONArray stops = this.query(getStopSql);
		for (int i = 0; i < stops.size(); i++) {
			JSONObject stop = stops.getJSONObject(i);
			stopMaps.put(stop.getString("stopId"), stop);
		}
		return stopMaps;
	}

	// 得到站点资源map
	public Map<String, JSONArray> getResourceOfStopMaps(String resourceType) {
		Map<String, JSONArray> resourceOfStopMaps = new HashMap<String, JSONArray>();
		String getResourceSql = "SELECT mr.RESOURCE_ID,mr.RESOURCE_NAME,mr.MEDIA_TYPE,mr.STATUS,mr.BUS_ID,mr.STOP_ID,ms.STOP_NAME,ms.ROAD_NAME,mt.MEDIA_NAME,mt.MEDIA_ID,mt.PARENT_ID  from  MEDIA_RESOURCE  mr "
				+ " LEFT JOIN MEDIA_TYPE mt  on mr.MEDIA_TYPE=mt.MEDIA_ID "
				+ " LEFT JOIN MEDIA_STOP ms on mr.STOP_ID=ms.STOP_ID "
				+ " WHERE mt.PARENT_ID="+Constant.MEDIA_TYPE_STOP+" and mt.STATUS = '" + Constant.DATA_STATUS_TRUE + "'";
		if(StringUtil.isNotEmpty(resourceType)){
			getResourceSql += " and mt.MEDIA_ID="+resourceType;
		}
		getResourceSql +=" order by mt.MEDIA_NAME ";
		
		JSONArray resources = this.query(getResourceSql);
		for (int i = 0; i < resources.size(); i++) {
			JSONObject resource = resources.getJSONObject(i);
			String stopId = resource.getString("stopId");
			JSONArray resourceArray = new JSONArray();
			if (!resourceOfStopMaps.containsKey(stopId)) {
				resourceArray.add(resource);
				resourceOfStopMaps.put(stopId, resourceArray);
			} else {
				resourceArray = resourceOfStopMaps.get(stopId);
				resourceArray.add(resource);
			}
		}
		return resourceOfStopMaps;
	}

	/**
	 * 获取站点资源树形结构数据
	 * 
	 * @return
	 */
	public JSONObject getResourceOfStopTree(ReqBean reqBean) {
		// 数据准备
		String resourceType = reqBean.getInfo("resourceType");
		Map<String, String> billResourceMap = getBidResourceMap(reqBean, resourceType);
		LinkedHashMap<String, JSONObject> stopMaps = getStopMaps(reqBean);
		Map<String, JSONArray> resourceOfStopMaps = getResourceOfStopMaps(resourceType);

		JSONArray array = new JSONArray();
		// 循环站点（第一层节点）
		for (Entry<String, JSONObject> entry : stopMaps.entrySet()) {
			// 线路节点d
			JSONObject o1 = new JSONObject();
			o1.put("id", entry.getKey());
			o1.put("pId", 0);
			o1.put("name", entry.getValue().getString("stopName"));
			if(Constant.DATA_STATUS_FALSE.equals( entry.getValue().getString("status"))){// 资源无效
				o1.put("chkDisabled", true);// 无效的资源不能勾选
			}
			// 循环站点对应的资源（第二层节点）
			JSONArray resourceArray = resourceOfStopMaps.get(entry.getKey());
			if (resourceArray != null) {
				for (int k = 0; k < resourceArray.size(); k++) {
					JSONObject resource = resourceArray.getJSONObject(k);
					// 具体资源节点
					JSONObject o2 = new JSONObject();
					o2.put("id", resource.getString("resourceId"));
					o2.put("pId", resource.getString("stopId"));
					o2.put("name", resource.getString("resourceName"));
					o2.put("stopName", resource.getString("stopName"));// 站点名称
					o2.put("roadName", resource.getString("roadName"));// 道路名称
					o2.put("mediaId", resource.getString("mediaId"));// 类型id
					o2.put("mediaName", resource.getString("mediaName"));// 类型名称
					o2.put("parentId", resource.getString("parentId"));// 类型父id
					if(Constant.DATA_STATUS_FALSE.equals(resource.getString("status"))){// 资源无效
						o2.put("chkDisabled", true);// 无效的资源不能勾选
					}
					if (billResourceMap.containsKey(resource.getString("resourceId"))) {// 订单对应的资源
						o2.put("chkDisabled", true);
						/*o2.put("open", true);
						o1.put("checked", true);
						o1.put("open", true);*/
					}
					//o2.put("icon", THIRD_FLOOR_ICON);
					array.add(o2);
				}
				//o1.put("iconOpen", FIRST_FLOOR_ICON_OPEN);
				//o1.put("iconClose", FIRST_FLOOR_ICON_CLOSE); 
				array.add(o1);
			}
		}
		JSONObject result = new JSONObject();
		result.put("array", array);
		return result;
	}

	public void addResourceOfBill(ReqBean reqBean) {
		String bidId = reqBean.getInfo("bidId");
		JSONArray array = JSONArray.fromObject(reqBean.getInfoObj("resourceDatas"));
		Map<String, String>  resIdToBidIdMap = new  HashMap<String, String>(); 
		// 新增、修改
		for (int i = 0; i < array.size(); i++) {
			JSONObject resource = array.getJSONObject(i);
			BiddingResource biddingResource = new BiddingResource();
			String resourceId = resource.getString("resourceId");
			String resourcePrice = resource.getString("resourcePrice");
			String startDate = resource.getString("startDate");
			String endDate = resource.getString("endDate");
			
			biddingResource.setBidId(bidId);
			biddingResource.setResourceId(resourceId);
			biddingResource.setResourcePrice(resourcePrice);
			biddingResource.setStartDate(DateUtil.parse(startDate));
			biddingResource.setEndDate(DateUtil.parse(endDate));
			BiddingResource res =biddingResourceMapper.selectByPrimaryKey(bidId, resourceId);
			if(res!=null){// 修改
				biddingResourceMapper.updateByPrimaryKeySelective(biddingResource);
			}else {// 新增
				biddingResourceMapper.insert(biddingResource);
			}
			resIdToBidIdMap.put(resource.getString("resourceId"), resource.getString("bidId"));
		}
			toDeleteResource(bidId,resIdToBidIdMap);// 删除
	}

	public void toDeleteResource(String bidId,Map<String, String> resIdToBidIdMap) {
		JSONArray resourceOfBidArray = new JSONArray();
		if(StringUtil.isNotEmpty(bidId)){
			String getResourceOfBidSlq = " select  abr.*  from AD_BIDDING_RESOURCE abr "
					+ " LEFT JOIN MEDIA_RESOURCE mr on abr.RESOURCE_ID=mr.RESOURCE_ID "
					+ " LEFT JOIN MEDIA_TYPE mt on mr.MEDIA_TYPE=mt.MEDIA_ID " + " where abr.bid_id=" + bidId;
			 resourceOfBidArray = this.query(getResourceOfBidSlq);
		}
		for (int i = 0; i < resourceOfBidArray.size(); i++) {
			JSONObject o = resourceOfBidArray.getJSONObject(i);
			String resourceId = o.getString("resourceId");
			if (!resIdToBidIdMap.containsKey(resourceId)) {// 待删除节点
				biddingResourceMapper.deleteByPrimaryKey(bidId,resourceId);
			}
		}
	}
	
	//获取资源已被占用的最大时间
	public JSONObject verifyResourceDate(ReqBean reqBean){
		String bidid = reqBean.getInfo("bidId");
		JSONArray nodesData = JSONArray.fromObject(reqBean.getInfoObj("nodesData"));
		Map<String, JSONObject> resIdToEndDateMaps = new HashMap<String, JSONObject>();
		JSONArray  resIdToEndDateArray = new JSONArray();
		for (int i = 0; i < nodesData.size(); i++) {
			JSONObject node = nodesData.getJSONObject(i);
			String resourceId = node.getString("resourceId");
			// 统计竞价单中资源的时间
			SqlBuilder getBidResourcesSql = new SqlBuilder("SELECT  abr.*,mr.RESOURCE_NAME  from  AD_BIDDING_RESOURCE   abr "
			+ " LEFT JOIN MEDIA_RESOURCE  mr on  abr.RESOURCE_ID=mr.RESOURCE_ID where  abr.RESOURCE_ID='"+resourceId+"'");
			if(StringUtil.isNotEmpty(bidid)){
				getBidResourcesSql.appendSql(" and abr.BID_ID <> "+bidid);	
			}
			JSONArray bidResources = this.query(getBidResourcesSql);
			if(bidResources != null && bidResources.size()>0){
				for (int j = 0; j < bidResources.size(); j++) {
					JSONObject  o = bidResources.getJSONObject(j);
					String resId = o.getString("resourceId");
					String endDate = o.getString("endDate");
					if(resIdToEndDateMaps.containsKey(resId)){
						Date oldEndDate = DateUtil.parse(resIdToEndDateMaps.get(resId).getString("endDate"));
						Date newEndDate = DateUtil.parse(endDate);
						if(newEndDate.after(oldEndDate)){
							resIdToEndDateMaps.put(resId, o);
						}
					}else {
						resIdToEndDateMaps.put(resId, o);
					}
				}
			}
			// 统计合同中资源的时间
			SqlBuilder getContractResourcesSql = new SqlBuilder("SELECT   acr.*,mr.RESOURCE_NAME  from  AD_CONTRACT_RESOURCE acr "
					+ " LEFT JOIN MEDIA_RESOURCE  mr on  acr.RESOURCE_ID=mr.RESOURCE_ID where  acr.RESOURCE_ID='"+resourceId+"'");
			JSONArray contractResources = this.query(getContractResourcesSql);
			if(contractResources != null && contractResources.size()>0){
				for (int m = 0; m < contractResources.size(); m++) {
					JSONObject  o = contractResources.getJSONObject(m);
					String resId = o.getString("resourceId");
					String endDate = o.getString("endDate");
					if(resIdToEndDateMaps.containsKey(resId)){
						Date oldEndDate = DateUtil.parse(resIdToEndDateMaps.get(resId).getString("endDate"));
						Date newEndDate = DateUtil.parse(endDate);
						if(newEndDate.after(oldEndDate)){
							resIdToEndDateMaps.put(resId, o);
						}
					}else {
						resIdToEndDateMaps.put(resId, o);
					}
				}	
			}
			
			for (Entry<String, JSONObject> entry : resIdToEndDateMaps.entrySet()) {
				JSONObject data = new JSONObject();
				data.put("resourceId", entry.getKey());
				data.put("endDate", DateUtil.formatDate(DateUtil.parse(entry.getValue().getString("endDate"))));
				data.put("resourceName", entry.getValue().getString("resourceName"));
				resIdToEndDateArray.add(data);
			}  
		}
		JSONObject  result = new JSONObject();
		result.put("resIdToEndDateArray", resIdToEndDateArray);
		return result;
	}
	
}